﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using LetsDoIt.BO;
using LetsDoIt.Controls;
using LetsDoIt.Interfaces;
using LetsDoIt.Localization;
using Microsoft.WindowsMobile.Forms;
using LetsDoIt.Common;

namespace LetsDoIt.Forms
{
	public partial class PhotosForm : UserControl, INavigationForm
	{
        private PictureBoxEx CurrentPicture;
        private int picCount = 1;
	    private CaseForm frmCase;
		public string ID { get; set; }
		private List<string> photoList;
		public List<string> PhotoList
		{
			get { return photoList; }
			set
			{
				photoList = value;
				if(photoList!=null)
				{
					foreach (Control ctrl in panelPhotos.Controls)
					{
						panelPhotos.Controls.Remove(ctrl);
						ctrl.Dispose();
					}
					GC.Collect();
					GC.WaitForPendingFinalizers();
					//
					foreach (string file in photoList)
					{
					    try
					    {
                            PictureBoxEx pic1 = new PictureBoxEx();
                            pic1.ForeColor = Color.Red;
                            using (Bitmap bmp = new Bitmap(Path.Combine(WastesLocalFactory.CasesStorePath(), file)))
                            {
                                pic1.Image = bmp;
                            }
                            pic1.Tag = file;
                            pic1.MouseDown += new MouseEventHandler(pic1_MouseDown);
                            int picWidth = (panelPhotos.Width / 2) - 4;
                            pic1.Size = new Size(picWidth, picWidth);
                            panelPhotos.Controls.Add(pic1);
					    }
					    catch (Exception ex)
					    {
					        Program.Log.Error(ex);
					    }
					}
                    ReorderPhotosInPanel();
					picCount = photoList.Count + 1;
				}
			}
		}


		#region Implementation of INavigationForm

		public MainForm HostForm { get; set; }
		public string Identity { get; set; }
        public bool IsActive { get; set; }

		public void NavigationEnter(object sender)
		{
			//nothing
			frmCase = HostForm.GetFormByIdentity(NavigationForms.FORM_CASE) as CaseForm;
			if (frmCase!=null)
				ID = frmCase.Case.ID;
            //update context menu
            HostForm.UpdateResources();
            HostForm.UpdateMenus(ctxPhotoMenu.MenuItems);
            Application.DoEvents();
		}

		public void NavigationLeave()
		{
			//nothing
		}

		#endregion


		#region ctor

		public PhotosForm(MainForm hostForm, string identity)
		{
			HostForm = hostForm;
			Identity = identity;
			InitializeComponent();
			photoList = new List<string>();

            AddMenusToDictionary();
		}

		#endregion ctor


        protected void AddMenusToDictionary()
        {
            HostForm.AddMenuToDictionary(this.mnuSetCaseIcon, "PhotosForm_SetCaseIcon");
            HostForm.AddMenuToDictionary(this.mnuDeletePhoto, "PhotosForm_DeletePhoto");
        }

		#region events
		private void btnTakePhoto_Click(object sender, EventArgs e)
		{
			CameraCaptureDialog capture = new CameraCaptureDialog();
            //TODO - try to detect a better resolution
            if (HostForm.Settings.PhotoWidth > 0 && HostForm.Settings.PhotoHeight > 0)
            {
                capture.Resolution = new Size(HostForm.Settings.PhotoWidth, HostForm.Settings.PhotoHeight);   
            }
            else
            {
                capture.Resolution = new Size(2 * 640, 2 * 480);    
            }
		    capture.StillQuality = CameraCaptureStillQuality.High;
		    capture.Title = ResourceManager.Instance.GetString(@"DialogCapturePhotoTitle");
			capture.InitialDirectory = WastesLocalFactory.CasesStorePath();
			string fileName = ID + "_" + picCount.ToString() + ".jpg";
		    while (File.Exists(fileName))
		    {
		        picCount++;
                fileName = ID + "_" + picCount.ToString() + ".jpg";
		    }
            //
			capture.DefaultFileName = fileName;
			capture.Mode = CameraCaptureMode.Still;
			if (capture.ShowDialog() == DialogResult.OK)
			{
				PhotoList.Add(Path.GetFileName(capture.FileName));
				PictureBoxEx pic1 = new PictureBoxEx();
				pic1.ForeColor = Color.Red;
			    using (Bitmap bmp = new Bitmap(capture.FileName))
			    {
                    pic1.Image = bmp;
			    }
				pic1.Tag = capture.FileName;
				pic1.MouseDown += new MouseEventHandler(pic1_MouseDown);
				int picWidth = (panelPhotos.Width/2) - 4;
				pic1.Size = new Size(picWidth, picWidth);
				panelPhotos.Controls.Add(pic1);
				ReorderPhotosInPanel();
				picCount++;
				//
                WastesLocalFactory.SaveLocalCase(frmCase.Case);
                //repopulate photo list after save
			    this.PhotoList = frmCase.Case.Pictures;
			}
			else
			{
				if(File.Exists(fileName))
					File.Delete(fileName);
			}
            capture.Dispose();
		}


		void pic1_MouseDown(object sender, MouseEventArgs e)
		{
			CurrentPicture = sender as PictureBoxEx;
			if (CurrentPicture != null)
			{
				foreach (Control ctrl in panelPhotos.Controls)
				{
					PictureBoxEx pic = ctrl as PictureBoxEx;
					if(pic!=null)
					{
						pic.Selected = (pic == CurrentPicture);
						pic.Invalidate();
					}
				}
				Application.DoEvents();
				ctxPhotoMenu.Show(CurrentPicture, new Point(e.X, e.Y));
			}
		}

		private void btnBack_Click(object sender, EventArgs e)
		{
			HostForm.NavigateBack(this, string.Empty);
		}

		private void mnuDeletePhoto_Click(object sender, EventArgs e)
		{
			//delete current photo
			if (CurrentPicture != null)
			{
				if (MessageBox.Show(
                    ResourceManager.Instance.GetString(@"DialogDeletePhotoConfirmation"),
                    ResourceManager.Instance.GetString(@"DialogDeleteTitleConfirmation"),
                    MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Yes)
				{
					string imageName = CurrentPicture.Tag.ToString();
					PhotoList.Remove(imageName);
					panelPhotos.Controls.Remove(CurrentPicture);
					ReorderPhotosInPanel();
					//
					SetCaseDirty();
					//
                    if (File.Exists(Path.Combine(WastesLocalFactory.CasesStorePath(), imageName)))
                        File.Delete(Path.Combine(WastesLocalFactory.CasesStorePath(), imageName));
					//update case and save it
                    if (frmCase.Case.Pictures.Contains(imageName))
                        frmCase.Case.Pictures.Remove(imageName);
				    WastesLocalFactory.SaveLocalCase(frmCase.Case);
				}
			}
		}

		private void mnuSetCaseIcon_Click(object sender, EventArgs e)
		{
			PhotoList.Remove(CurrentPicture.Tag.ToString());
			PhotoList.Insert(0, CurrentPicture.Tag.ToString());
			panelPhotos.Controls.SetChildIndex(CurrentPicture, 0);
			ReorderPhotosInPanel();
			//
			SetCaseDirty();
		}

		private void SetCaseDirty()
		{
			CaseForm caseForm = HostForm.GetFormByIdentity(NavigationForms.FORM_CASE) as CaseForm;
			caseForm.IsDirty = true;
		}

		#endregion events


		#region methods

		private void ReorderPhotosInPanel()
		{
			int count = 0;
			int picWidth = (panelPhotos.Width/2) - 4;
			foreach(Control ctrl1 in panelPhotos.Controls)
			{
				ctrl1.Location = new Point((count % 2 == 0 ? 2 : 6 + picWidth), 2+ (4 + picWidth) * (int)(count++ / 2));
			}
		}

		public void ResetPhotos()
		{
			PhotoList.Clear();
			panelPhotos.Controls.Clear();
			ReorderPhotosInPanel();
			picCount = 1;
		}

		#endregion methods

	}
}
